﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Updating;
using DevExpress.Xpo;

namespace EasyXaf.DataDictionaries;

public class DataDictionaryUpdater : ModuleUpdater
{
    public DataDictionaryUpdater(IObjectSpace objectSpace, Version currentDBVersion)
        : base(objectSpace, currentDBVersion)
    {
    }

    public override void UpdateDatabaseAfterUpdateSchema()
    {
        base.UpdateDatabaseAfterUpdateSchema();

        // 收集XAF中的所有数据字典名称，并创建对应的数据字典
        // 收集思路与Module类中CustomizeTypesInfo方法类似，请参考其中的注释
        // 注意：这里并没有对其进行过滤，只要有DataDictionaryAttribute都会被收集

        var typesInfo = ObjectSpace.TypesInfo;
        var dataDictionaryNames = new List<string>();

        foreach (var persistentTypeInfo in typesInfo.PersistentTypes)
        {
            var members = persistentTypeInfo.Members.Where(m => m.MemberType == typeof(XPCollection<DataDictionaryItem>) || m.MemberType == typeof(DataDictionaryItem));
            foreach (var member in members)
            {
                var attribute = member.FindAttribute<DataDictionaryAttribute>();
                if (attribute != null && !string.IsNullOrWhiteSpace(attribute.DataDictionaryName))
                {
                    if (!dataDictionaryNames.Contains(attribute.DataDictionaryName))
                    {
                        dataDictionaryNames.Add(attribute.DataDictionaryName);
                    }
                }
            }
        }

        foreach (var dataDictionaryName in dataDictionaryNames)
        {
            var dataDictionary = ObjectSpace.FirstOrDefault<DataDictionary>(d => d.Name == dataDictionaryName);
            if (dataDictionary == null)
            {
                dataDictionary = ObjectSpace.CreateObject<DataDictionary>();
                dataDictionary.Name = dataDictionaryName;
            }
        }

        ObjectSpace.CommitChanges();
    }
}
